package cn.tedu.gateway.filter;

import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

//@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {
    //全局过滤器的判断逻辑
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.从请求中获取token参数
        String token = exchange.getRequest().getQueryParams().getFirst("token");
        //2.获取请求中的token，判断token是否为admin
        if(!StringUtils.equals(token,"admin")){ //通过"!"取反
            System.out.println("鉴权失败！！！");
            //阻止向后转发，设置响应状态码
            exchange.getResponse().setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
            //完成响应
            return exchange.getResponse().setComplete();
        }
        //3.鉴权成功，继续向后执行
        return chain.filter(exchange);
    }

    //顺序，数值越小，该方法越早执行
    @Override
    public int getOrder() {
        return 0;
    }
}
